package com.yz.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yz.common.annotation.Login;
import com.yz.common.entity.CloudStorageConfig;
import com.yz.common.entity.ConfigEntity;
import com.yz.common.entity.contant;
import com.yz.common.utils.R;
import com.yz.service.ConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.yz.common.entity.contant.url_prix;


@RestController
@RequestMapping("/api")
@Api(tags="上传接口")
public class ApiUploadController {
    @Autowired
    ConfigService configService;
    @Value("${spring.profiles.active}")
    private String profilesActive;
    Logger logger = LoggerFactory.getLogger(ApiUploadController.class);

    @ApiOperation("提交文件")
    @Login
    @RequestMapping("/upload")
    public R fileUpload(@RequestHeader("token")String token, @RequestParam("file") MultipartFile file)
    {
        System.out.println(file.getOriginalFilename() + ", size:" + file.getSize());
        ConfigEntity configString = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("`key`","CLOUD_STORAGE_CONFIG_KEY"));
        HashMap<String,Object> config = (HashMap<String,Object>) JSONUtils.parse(configString.getValue());
        String prix = "";
        String url_prix ="";
        if(profilesActive.equals("dev")){
            prix = contant.prix;
            url_prix =contant.url_prix;
        }else{
            prix = (String)config.get("nginxServerPath");
            url_prix =(String)config.get("nginxDomain");
        }
        String uuid = UUID.randomUUID()+file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
        // 上传到SSO服务
        try {
            file.transferTo(new File(prix + File.separator + uuid));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 返回公网地址
        Map<String,Object> map = new HashMap<>();
        map.put("url", url_prix + uuid);
        return R.ok().put("data",map);
    }


}
